﻿using System.Linq;
using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class ContentPreviewPresenter : BasePresenter
    {
        private readonly IContentPreviewView _view;
        
        public ContentPreviewPresenter(IContentPreviewView view)
            : this(view, new RepositoryFactory())
        {
        }

        public ContentPreviewPresenter(IContentPreviewView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
        }

        public void Initialize()
        {
            Content content = ContentRepository.GetContent(_view.ContentID);
            if (content != null)
            {
                if (_view.VersionID > 0)
                {
                    _view.SetHtml(ContentRepository.GetContentTranslationVersion(_view.VersionID).Html);
                }
                else
                {
                    ContentTranslation translation = null;
                    if (content.Translations.ContainsKey(_view.LocaleID))
                        translation = content.Translations[_view.LocaleID];
                    if (translation != null && translation.Versions.Count > 0 && translation.PublishedVersion == null)
                        _view.SetHtml(translation.Versions.Last().Html);
                    else
                        _view.SetHtml(content.GetPublishedHtml(_view.LocaleID));
                }
            }
            _view.SetStylesheets(
                SiteRepository.GetMasterTemplate(_view.MasterTemplateID).GetStylesheets().Where(
                    stylesheet => stylesheet.Context == StylesheetContext.Always));
        }
    }
}